package com.aaa.fees.service.ipml;

import cn.hutool.core.bean.BeanUtil;
import com.aaa.entity.*;
import com.aaa.fees.dao.*;
import com.aaa.fees.service.PayChargeService;
import com.aaa.fees.utils.HttpClient;
import com.aaa.fees.vo.PostObjVo;
import com.aaa.fees.vo.PostObjVo1;
import com.aaa.fees.vo.PostObjVo2;
import com.aaa.util.IdWorker;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class PayChargeServiceImpl  implements PayChargeService {
    @Autowired
    PayChargeDao payChargeDao;
    @Autowired
    ChargeDao chargeDao;
    @Autowired
    ChargeItemDao chargeItemDao;
    @Autowired
    CareOrderDao careOrderDao;
    @Autowired
    CareOederItemDao careOederItemDao;
    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.mch_id}")
    private String mchId;
    @Value("${weixin.api_key}")
    private String apiKey;


    @Override
    public Result<Map<String, Object>> queryByIdHistory(String regId) {

        //根据前端穿过来的reg_id查询病历表信息
        QueryWrapper<CareHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("reg_id", regId);
        CareHistory careHistory = payChargeDao.selectOne(wrapper);
        if (careHistory == null) {
            return new Result<>(5000, "请输入未支付的挂号单", null);
        }
        //获取到ch_id查询药用处方表信息
        String chId = careHistory.getChId();
        QueryWrapper<CareOrder> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("ch_id", chId);
        List<CareOrder> careOrders = careOrderDao.selectList(wrapper1);
        List<Map<String, Object>> list = new ArrayList<>();
        if (careOrders.size() > 0) {
            for (CareOrder careOrder : careOrders) {
                Map<String, Object> map = BeanUtil.beanToMap(careOrder);
                QueryWrapper<CareOrderItem> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("co_id", careOrder.getCoId());
                wrapper2.eq("status", 0);
                List<CareOrderItem> careOrderItems = careOederItemDao.selectList(wrapper2);
                //计算订单总金额
                if (careOrderItems.size() != 0) {
                    Double sum = careOrderItems.stream().map(item -> item.getAmount().doubleValue()).reduce((a, b) -> a + b).get();
                    map.put("careOrderItems", careOrderItems);
                    map.put("sum", sum);
                    list.add(map);
                }
            }

        }
        if (list.isEmpty()) {
            return new Result<>(5000, "请输入未支付的订单ID", null);
        } else {
            //把数据存放在map中返回
            Map<String, Object> maps = new HashMap<>();
            maps.put("careHistory", careHistory);
            maps.put("list", list);
            return new Result<>(200, "查询数据成功", maps);
        }
    }

    //现金支付
    @Override
    @Transactional
    public Result<CareOrderItem> createOrderChargeWithCash(PostObjVo postObjVo) {
        //获取挂号单id
        String regId=postObjVo.getOrderChargeDto().getRegId();
        //获取患者姓名
        String patientName=postObjVo.getOrderChargeDto().getPatientName();
        //获取总金额
        BigDecimal orderAmount = postObjVo.getOrderChargeDto().getOrderAmount();
        //创建时间
        LocalDateTime createTime = LocalDateTime.now();
        //生成orderId
        String orderId="ODB";
//        long l = new IdWorker().nextId();
//        String oid =l+orderId;
        Random random = new Random();
        for (int i = 0; i <19 ; i++) {
            orderId+=String.valueOf(random.nextInt(10));
        }
        //将前端传过来的数据存在收费表 his_order_charge
        chargeDao.insertAll(orderId,regId,patientName,orderAmount,createTime);

        //获取itemId  修改支付状态
        List<PostObjVo1> orderChargeItemDtoList = postObjVo.getOrderChargeItemDtoList();
        for (int i=0;i<orderChargeItemDtoList.size();i++){
            //支付成功 修改开诊细表状态为已支付 his_care_order_item
            careOederItemDao.updateByStatus(orderChargeItemDtoList.get(i).getItemId());
        }
        for (int i=0;i<orderChargeItemDtoList.size();i++){
            ChargeItem chargeItem = new ChargeItem();
            chargeItem.setOrderId(orderId);
            chargeItem.setItemId(orderChargeItemDtoList.get(i).getItemId());
            chargeItem.setItemType(orderChargeItemDtoList.get(i).getItemType());
            chargeItem.setItemName(orderChargeItemDtoList.get(i).getItemName());
            chargeItem.setItemNum(orderChargeItemDtoList.get(i).getItemNum());
            chargeItem.setItemPrice(orderChargeItemDtoList.get(i).getItemPrice());
            chargeItem.setItemAmount(orderChargeItemDtoList.get(i).getItemAmount());
            chargeItem.setCoId(orderChargeItemDtoList.get(i).getCoId());
            chargeItem.setStatus("1");
            //支付成功将数据存放在收费表查看弹层的支付订单详情页 his_order_charge_item
            chargeItemDao.insert(chargeItem);
        }
        return new Result<>(200,"支付成功");
    }


    //微信收费
    @Override
    public Result handlePayWithZfb(PostObjVo postObjVo) {
        //获取患者姓名
        String patientName=postObjVo.getOrderChargeDto().getPatientName();
        String regId=postObjVo.getOrderChargeDto().getRegId();
        //生成订单号orderId
        String orderId="ODB";
        Random random = new Random();
        for (int i = 0; i <19 ; i++) {
            orderId+=String.valueOf(random.nextInt(10));
        }
        //获取总金额
        BigDecimal orderAmount = postObjVo.getOrderChargeDto().getOrderAmount();
        try {
            //设置请求的参数
            Map<String, String> params = new HashMap<>();//请求参数
            params.put("appid", appId);
            params.put("mch_id", mchId);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            params.put("body", patientName);//标题
            params.put("out_trade_no", orderId);
            //支付金额0.01 未来换成真是的金额
            params.put("total_fee", new BigDecimal(0.01 ).multiply(new BigDecimal(100)).longValue()+"");
            params.put("spbill_create_ip", "127.0.0.1");//未来写成项目部署的ip
            params.put("notify_url", "http:localhost:8080/charge/docharge");
            params.put("trade_type", "NATIVE");
            //创建httpClient对象 作用远程调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //支持https协议
            client.setHttps(true);
            //设置请求参数
            client.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
            //发送请求
            client.post();
            //获取请求的响应结果
            String content = client.getContent();
            System.out.println("============================+"+content);

            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if (map.get("result_code").equals("SUCCESS")){
                Map<String,Object> result=new HashMap<>();
                result.put("codeUrl",map.get("code_url"));
                result.put("price",orderAmount);
                result.put("orderId",orderId);
                //创建时间
                LocalDateTime createTime = LocalDateTime.now();
                //将前端传过来的数据存在收费表 his_order_charg

                chargeDao.insertZFB(orderId,regId,patientName,orderAmount,createTime);


                //获取itemId  修改支付状态
                List<PostObjVo1> orderChargeItemDtoList = postObjVo.getOrderChargeItemDtoList();
                for (int i=0;i<orderChargeItemDtoList.size();i++){
                    //创建订单后  修改开诊细表状态为已完成  his_care_order_item
                    //careOederItemDao.updateByZFBStatus(orderChargeItemDtoList.get(i).getItemId());
                }
                for (int i=0;i<orderChargeItemDtoList.size();i++){
                    ChargeItem chargeItem = new ChargeItem();
                    chargeItem.setOrderId(orderId);

//                    IdWorker idWorker = new IdWorker();
//                    String s = idWorker.nextId() + "ql1";
                    chargeItem.setItemId(orderChargeItemDtoList.get(i).getItemId());
//                    chargeItem.setItemId(s);
                    chargeItem.setItemType(orderChargeItemDtoList.get(i).getItemType());
                    chargeItem.setItemName(orderChargeItemDtoList.get(i).getItemName());
                    chargeItem.setItemNum(orderChargeItemDtoList.get(i).getItemNum());
                    chargeItem.setItemPrice(orderChargeItemDtoList.get(i).getItemPrice());
                    chargeItem.setItemAmount(orderChargeItemDtoList.get(i).getItemAmount());
                    chargeItem.setCoId(orderChargeItemDtoList.get(i).getCoId());
                    chargeItem.setStatus("0");
                    //生成二维码 将数据存放在收费表查看弹层的支付订单详情页 his_order_charge_item
                    chargeItemDao.insert(chargeItem);
                }
                return new Result(200,"生成二维码成功",result);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(200,"订单失效了",null);
    }

    //查询订单是否支付
    @Override
    public Result queryOrderChargeOrderId(String orderId) {

        try {
            //根据订单状态查询微信的支付的状态
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            Map<String, String> params = new HashMap<>();
            params.put("appid", appId);
            params.put("mch_id", mchId);
            params.put("out_trade_no", orderId);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
            client.post();
            String content = client.getContent();
            System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+content);
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if (map.get("trade_state").equals("SUCCESS")){ //二维码支付成功 开始修改订单
                chargeDao.updateByIdOrderCharge(orderId);
                QueryWrapper<ChargeItem> wrapper=new QueryWrapper<>();
                wrapper.eq("order_id",orderId);
                List<ChargeItem> orderChargeItems = chargeItemDao.selectList(wrapper);
                for (int i = 0; i < orderChargeItems.size(); i++) {
                    chargeItemDao.updataBystatus(orderId);
                }
                return new Result(200,"支付成功",true);
            }
        }catch (Exception e){
        }
        return  new Result(200,"请重新扫描二维码支付",false);
    }
}